# http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E6%9E%97%E5%BF%97%E6%9E%97

import requests, re, os, uuid, urllib3
from datetime import datetime


def getuuid():
    # 获取唯一加密值，uuid1 根据主机mac地址和时间戳生成全球唯一加密值唯一缺点会暴露mac地址
    id = uuid.uuid1()
    # 将生成的加密值去除-获得32位加密值
    # id = id.replace('-', '')
    return str(id)


#
def download_img(url, dir):
    # 1、查看网址源代码，图片地址在哪里，进行正则匹配
    html = requests.get(url).text
    # 正则匹配
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    for each in pic_url:
        print('下载地址 ' + each + ' dir ' + dir)
        if len(each) < 10:
            return
        try:
            pic = requests.get(each, timeout=10)
            i = i + 1
            print('pic--- ', i)
        except requests.exceptions.ConnectionError:
            print('ConnectionError')
            continue
        except requests.exceptions.ReadTimeout:
            print('requests.exceptions.ReadTimeout')
            continue
        except urllib3.exceptions.ReadTimeoutError:
            print('urllib3.exceptions.ReadTimeoutError')
            continue
        path = 'G:\\python案例\\mypic\\' + dir  # 设置图片的保存地址
        if not os.path.isdir(path):
            os.makedirs(path)  # 判断没有此路径则创建
        paths = path + '\\'  # 保存路径下
        # 重新给图片命名
        dirpic = paths + 'time_' + getuuid() + '.jpg'
        fp = open(dirpic, 'wb')
        fp.write(pic.content)
        fp.close()


if __name__ == '__main__':
    # url = "http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E6%9E%97%E5%BF%97%E6%9E%97"
    url = "http://image.baidu.com/search/index?ct=201326592&z=&tn=baiduimage&word=%E6%9E%97%E5%BF%97%E7%8E%B2&pn=0&ie=utf-8&oe=utf-8&cl=2&lm=-1&fr=&se=&sme=&width=1920&height=1080&hd=1&latest=0&copyright=0"

    download_img(url, '图片保存')
